#include <tsin/library/TouhouEnemySeries.hpp>

#include <tsin/library/BuiltinImages.hpp>

#include <tsin/util/Logger.hpp>

using namespace tsin;

static const int TICKS_PER_FRAME = 6;
static const int TOTAL_FRAMES = 4;

static void animation(DecoratedImage *image, int prevTick, int curTick)
{
        int prevFrame = prevTick / TICKS_PER_FRAME;
        int curFrame = curTick / TICKS_PER_FRAME;
        if (prevFrame == curFrame)
                return;

        float l = image->left(), r = image->right(), w = image->width();
        int relative = curFrame - prevFrame;
        image->setXRange(l + relative*w, r + relative*w);
}

static void idleAnimation(DecoratedImage *image, int prevTick, int curTick)
{
        if (curTick == image->nrFrames()) {
                image->setFrame(0, false);
                curTick = 0;
        }
        animation(image, prevTick, curTick);
}

static void moveAnimation(DecoratedImage *image, int prevTick, int curTick)
{
        if (curTick == image->nrFrames()) {
                image->setFrame(prevTick, false);
                return;
        }
        animation(image, prevTick, curTick);
}

static void chargeAnimation(DecoratedImage *image, int prevTick, int curTick)
{
        if (curTick == image->nrFrames()) {
                int next = 2 * TICKS_PER_FRAME;
                image->setFrame(next, false);
                curTick = next;
        }
        animation(image, prevTick, curTick);
}

const char *TouhouEnemySeries::getImagePath()
{
        return RES_PREFIX "boss/1206.png";
}

int TouhouEnemySeries::getSizeX()
{
        return 96;
}

int TouhouEnemySeries::getSizeY()
{
        return 128;
}

int TouhouEnemySeries::getCoordX()
{
        return 0;
}

int TouhouEnemySeries::getCoordY()
{
        switch(action) {
        case MOVE_LEFT:
                return 128;
        case MOVE_RIGHT:
                return 256;
        case CHARGE:
                return 0;
        default:
                return 384;
        }
}

int TouhouEnemySeries::getNrFrames()
{
        return TICKS_PER_FRAME * TOTAL_FRAMES;
}

NextFrameHandler TouhouEnemySeries::getHandler()
{
        switch(action) {
        case MOVE_LEFT:
        case MOVE_RIGHT:
                return moveAnimation;
        case CHARGE:
                return chargeAnimation;
        default:
                return idleAnimation;
        }
}
